package com.itmake.sample.server.monitor.util;

import cn.hutool.core.text.CharSequenceUtil;
import com.itmake.sample.server.monitor.model.vo.RedisInfoVo;
import org.springframework.data.redis.connection.RedisServerCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * redis 信息工具
 *
 * @author Amjacks
 * @since 2023/08/10
 */
@Component
public class RedisInfoUtil {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 获取 redis 详情
     * @return redis 详情
     */
    public RedisInfoVo getInfo() {
        Properties info = (Properties) redisTemplate.execute((RedisCallback<Object>) RedisServerCommands::info);
        Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info("commandstats"));
        Object dbSize = redisTemplate.execute((RedisCallback<Object>) RedisServerCommands::dbSize);

        RedisInfoVo cacheInfoVo = new RedisInfoVo();
        cacheInfoVo.setInfo(info);
        cacheInfoVo.setDbSize(dbSize);

        List<Map<String, String>> pieList = new ArrayList<>();
        if (Objects.nonNull(commandStats)) {
            commandStats.stringPropertyNames().forEach(key -> {
                Map<String, String> data = new HashMap<>(2);
                String property = commandStats.getProperty(key);
                data.put("name", CharSequenceUtil.removePrefix(key, "cmdstat_"));
                data.put("value", CharSequenceUtil.subBetween(property, "calls=", ",usec"));
                pieList.add(data);
            });
        }
        cacheInfoVo.setCommandStats(pieList);
        return cacheInfoVo;
    }
}
